package com.Cychat.chat.handler;

import com.Cychat.chat.util.WebSocketUtil;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * Auther: 刘博文  <br/>
 * Date: 2025/10/29:20:02  <br/>
 * Description: websocket处理类
 */
@Slf4j
@Component
@ServerEndpoint("/api/chat/{userId}")
public class WebSocketHandler {
	// 当前端连接上服务器时
	@OnOpen
	public void open(@PathParam("userId") String id, Session session){
		log.info("用户 {} 连接成功", id);
		// 放入map中
		WebSocketUtil.MESSAGEMAP.put(id, session);
		// 发送离线消息
		WebSocketUtil.sendOfflineMessages(id);
	}

	@OnMessage
	public void message(@PathParam("userId") String id, String message){
		// 将消息转换成对象
		WebSocketUtil.sendTo(message);
	}

	// 关闭连接
	@OnClose
	public void onClose(@PathParam("userId")String id,Session session) {
		//将当前用户从map中移除 注销
		WebSocketUtil.MESSAGEMAP.remove(id);
		//关闭session
		try {
			if (session != null && session.isOpen()) {
				session.close();
			}
		} catch (IOException e) {
			log.error("关闭WebSocket连接时出错: ", e);
		}
		log.info("用户 {} 断开连接", id);
	}
}
